package com.qf.interceptor;

import com.qf.exhandler.TokenException;
import com.qf.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1. 获取请求头中的token
        String token = request.getHeader("token");

        //2. 校验token的有效性
        if (token==null) {
            log.info("请求头中没有携带token，拦截器拦截了该请求path={}",request.getRequestURI());

            // 这里抛出异常，由Token的异常处理器进行异常捕获并返回json
//            throw new RuntimeException("请求头中没有携带token");
            TokenException tokenException = new TokenException();
            tokenException.setCode(-3);
            tokenException.setTokenMsg("请求头中没有携带token");
            throw tokenException;

//            return false; // 请求到此结束
        }

        if (!JwtUtils.checkToken(token)) {
            log.info("token校验失败了，拦截器拦截了该请求path={}",request.getRequestURI());
            TokenException tokenException = new TokenException();
            tokenException.setCode(-3);
            tokenException.setTokenMsg("token校验失败");
            throw tokenException;
//            throw new RuntimeException("请求头中没有携带token");
//            return false; // 请求到此结束
        }

        //3. 放行该请求
        log.info("token校验通过拉:请求的路径为path={}",request.getRequestURI());
        return true;


    }
}
